package com.example.treehole.fragmnet;

import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.io.Serializable;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment {
    public Unbinder unbinder;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(initLayout(),container,false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder= ButterKnife.bind(this,view);
        initData(view);
    }

    protected abstract int initLayout();

    protected abstract void initData(View view);


    public void showToast(String msg){
        Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
    }

    public void showToastSync(String msg){
        Looper.prepare();
        Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
        Looper.loop();
    }


    public void jumpTo(Class cls){
        Intent intent=new Intent(getActivity(),cls);
        startActivity(intent);
    }

    public <T> void jumpTo(Class cls, T data){
        Intent intent=new Intent(getActivity(),cls);
        Bundle bundle=new Bundle();
        bundle.putSerializable("data", (Serializable) data);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public <T> void jumpTo(Class cls, List<T> data){
        Intent intent=new Intent(getActivity(),cls);
        Bundle bundle=new Bundle();
        bundle.putSerializable("data", (Serializable) data);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    protected void saveStringToSp(String key,String value){
        SharedPreferences sp = getActivity().getSharedPreferences("treeHole",MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key,value);
        editor.apply();
    }

    protected String getStringFromSp(String key){
        SharedPreferences sp = getActivity().getSharedPreferences("treeHole",MODE_PRIVATE);
        return sp.getString(key,"");
    }
}
